package cn.edu.seig.springboot.controller;

import cn.edu.seig.springboot.model.User;
import cn.edu.seig.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        
        if (user.getUsername() == null || user.getPassword() == null || user.getRole() == null) {
            response.put("success", false);
            response.put("message", "用户名、密码和身份不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        User loginUser = userService.login(user.getUsername(), user.getPassword(), user.getRole());
        
        if (loginUser != null) {
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("user", loginUser);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户名或密码错误，或该账号已被禁用");
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Integer id) {
        Map<String, Object> response = new HashMap<>();
        User user = userService.getUserById(id);
        
        if (user != null) {
            response.put("success", true);
            response.put("user", user);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
    }
}
